package com.myjob.serviceImpl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.myjob.config.Constants;
import com.myjob.entity.*;
import com.myjob.exception.DBOptionException;
import com.myjob.mapper.OrderMapper;
import com.myjob.response.Result;
import com.myjob.service.*;
import com.myjob.utils.UtilValidate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;


/**
 * @author Chen Yuan
 */
@Slf4j
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private MemberService memberService;
    @Autowired
    private CompanyService companyService;

    @Override
    public Result selectOrder(Integer currentPage, Integer pageSize,
                              Long orderId, String companyName, String searchValue) {
        QueryWrapper<MemberOrder> wrapper = new QueryWrapper<>();
        Page<MemberOrder> page = null;

        if (UtilValidate.isNotEmpty(orderId)){
            wrapper.like("order_id", orderId);
        }
        if (UtilValidate.isNotEmpty(companyName)){
            wrapper.like("company_name", companyName);
        }
        if (UtilValidate.isNotEmpty(searchValue)) {
            wrapper.and(w -> w.like("company_name", searchValue)
                    .or().like("order_id", searchValue)
                    .or().like("member_level", searchValue));
        }

        wrapper.orderByDesc("create_date");
        if (UtilValidate.isEmpty(pageSize)){
            page = new Page<>(currentPage, Constants.getPageSize());
        }else {
            page = new Page<>(currentPage, pageSize);
        }

        IPage<MemberOrder> order = orderMapper.selectPage(page, wrapper);
        return Result.succeed(order);
    }

    @Override
    @Transactional(rollbackFor = DBOptionException.class)
    public Result addOrder(MemberOrder order) {
        if (UtilValidate.isEmpty(order)){
            return Result.failed("参数为空");
        }

        Result result = null;
        DateTime endDate = null;
        Member member = memberService.selectOneMember(order.getMemberLevel());
        Company company = companyService.selectOneCompany(order.getCompanyId());
        if (UtilValidate.isEmpty(company)){
            return Result.failed("企业信息异常");
        }
        Date memberEndDate = company.getMemberEndDate();
        Date inDate = company.getInDate();
        // 判断会员是否过期
        boolean isOver = DateUtil.isIn(memberEndDate, inDate, new Date());
        // 判断是否是升级会员
        boolean isSameLevel = company.getMemberLevel().equals(order.getMemberLevel());

        if (isOver || !isSameLevel){
            // 已经过期 或者 会员等级与之前不一致 ，会员开始、结束日期从付款时开始计算
            endDate = DateUtil.beginOfDay(DateUtil.offsetMonth(new Date(), order.getTerm()));
        }else {
            // 没有过期，会员开始、结束日期进行累加
            endDate = DateUtil.beginOfDay(DateUtil.offsetMonth(memberEndDate, order.getTerm()));
        }

        company.setMemberEndDate(endDate);
        company.setMemberLevel(member.getTypeName());

        order.setEndDate(endDate);
        order.setCompanyName(company.getCompanyName());

        log.info("===== 开始购买会员 =====");
        int insert = orderMapper.insert(order);
        log.info("===== 订单添加成功 =====");
        int update = companyService.updateCompany(company);
        log.info("===== 企业信息修改成功 =====");

        if (insert + update != 2){
            return Result.failed("会员购买失败");
        }

        if (isSameLevel){
            result = Result.succeed(order,"会员购买成功");
        }else {
            result = Result.warn(order,"会员购买成功,会员等级已修改");
        }
        return result;
    }
}